﻿using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class SaveComponent
{
    string filePath;
    Dictionary<string, string> pairs = new Dictionary<string, string>();

    public SaveComponent(string filePath)
    {
        this.filePath = filePath;
        Debug.Log($"SavePath: {filePath}");
        if (!File.Exists(filePath))
            return;
        Debug.Log("read file");
        var text = File.ReadAllText(filePath);
        try
        {
            pairs = LitJson.JsonMapper.ToObject<Dictionary<string, string>>(text);
        }
        catch(Exception ex)
        {
            Debug.LogError(ex);
        }
    }

    public bool HasKey(string key)
    {
        return pairs.ContainsKey(key);
    }

    public void DeleteKey(string key)
    {
        if (!pairs.ContainsKey(key))
            return;
        pairs.Remove(key);
    }

    public void DeleteAll()
    {
        pairs.Clear();
    }

    public void SaveAll()
    {
        try
        {
            var dir = Path.GetDirectoryName(filePath);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            File.WriteAllText(filePath, LitJson.JsonMapper.ToJson(pairs));
        }
        catch(Exception ex)
        {
            Debug.LogError(ex);
        }
    }

    public void SetInt(string key, int value)
    {
        if (pairs.ContainsKey(key))
        {
            pairs[key] = value.ToString();
            return;
        }
        pairs.Add(key, value.ToString());
    }
    public void SetFloat(string key, float value)
    {
        if (pairs.ContainsKey(key))
        {
            pairs[key] = value.ToString();
            return;
        }
        pairs.Add(key, value.ToString());
    }
    public void SetString(string key, string value)
    {
        if(pairs.ContainsKey(key))
        {
            pairs[key] = value;
            return;
        }
        pairs.Add(key, value);
    }

    public int GetInt(string key, int defaultValue = 0)
    {
        if (pairs.ContainsKey(key))
        {
            var str = pairs[key];
            int result;
            int.TryParse(str, out result);
            return result;
        }
        return defaultValue;
    }
    public float GetFloat(string key, float defaultValue = 0f)
    {
        if (pairs.ContainsKey(key))
        {
            var str = pairs[key];
            float result;
            float.TryParse(str, out result);
            return result;
        }
        return defaultValue;
    }
    public string GetString(string key, string defaultValue = "")
    {
        if (pairs.ContainsKey(key))
        {
            return pairs[key];
        }
        return defaultValue;
    }
}